/**
* @CopyRight tstudy.com.cn
* @author wuyahui
* @E-mail wuyahui0124505@163.com
* @version 1.0.0
* @Date  2015年4月3日 下午1:03:40
*/
package com.tstudy.laoshibang.community;

import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.apache.http.Header;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.tstudy.laoshibang.R;
import com.tstudy.laoshibang.base.BaseActivity;
import com.tstudy.laoshibang.base.BaseApplication;
import com.tstudy.laoshibang.base.BaseFragment;
import com.tstudy.laoshibang.base.BaseOnScrollListener;
import com.tstudy.laoshibang.base.BaseOnScrollListener.LoadMoreCallBack;
import com.tstudy.laoshibang.base.CONSTANT;
import com.tstudy.laoshibang.base.CONSTANT.LoadType;
import com.tstudy.laoshibang.base.HttpManager;
import com.tstudy.laoshibang.base.SplashActivity;
import com.tstudy.laoshibang.community.CommunityMessageListAdapter.AdapterCallBack;
import com.tstudy.laoshibang.manager.CommunityMessageManager;
import com.tstudy.laoshibang.mode.CommunityMessage;
import com.tstudy.laoshibang.mode.request.Conds;
import com.tstudy.laoshibang.mode.response.BaseResponse;
import com.tstudy.laoshibang.mode.response.CommunityMessageResponse;
import com.tstudy.laoshibang.profile.MyCommunityFragment;
import com.tstudy.laoshibang.utils.AppShortCutUtil;
import com.tstudy.laoshibang.utils.CommonUtil;
import com.tstudy.laoshibang.utils.LogUtil;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
@SuppressLint("InflateParams")
@EFragment(R.layout.community_message_list)
public class CommunityMessageListFragment extends BaseFragment{
	final static String TAG = "community_message_list";
	public CommunityMessageListFragment() {
		super();
	}
	
	@ViewById(R.id.community_message_list_root)
	RelativeLayout mRootLayout;
	
	@ViewById(R.id.community_message_list_progress)
	RelativeLayout mProgressLayout;
	
	@ViewById(R.id.community_message_list_list)
	PullToRefreshListView mPullToRefreshListView;
	
	@ViewById(R.id.community_message_list_empty_layout)
	RelativeLayout mEmptyLayout;
	
	BaseOnScrollListener mBaseOnScrollListener;
	LoadType mLoadType;
	
	boolean mIsFirstLoad = true;
	Handler mHandler;
	LayoutInflater mInflater;
	CommunityMessageListAdapter mCommunityMessageListAdapter;
	int mCurrentPosition = 0;
	List<View> mViewList = new ArrayList<View>();
	List<CommunityMessage> mCommunityMessages = new ArrayList<CommunityMessage>();
	@StringRes(R.string.select_all)
	String mSelectAllStr;
	int mSelectAllKey = -1;
	String mUserNo;
	boolean mHasUnRead;

	public static void add(String userNo,boolean hasUnRead,int containerViewId) {
		Bundle args = new Bundle();
		args.putInt(CONSTANT.ARGS.FRAGMENT_ID, containerViewId);
		args.putString(CONSTANT.ARGS.USER_NO, userNo);
		args.putBoolean(CONSTANT.ARGS.HAS_UNREAD, hasUnRead);
		Fragment fragment = Fragment.instantiate(BaseApplication.mContext,CommunityMessageListFragment_.class.getName(),args);
		((BaseActivity)BaseApplication.mCurrentActivity).add(containerViewId,fragment,TAG);	
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		mHandler = new Handler();
		super.onCreate(savedInstanceState);
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mInflater = inflater;
		super.onCreateView(inflater, container, savedInstanceState);
		LogUtil.d("--mBaseLayout==" + mRootLayout);
		mIsFirstLoad = mRootLayout == null;
		if (mRootLayout != null) {
			((ViewGroup) mRootLayout.getParent()).removeAllViews();
		}
		return mRootLayout;
	}
	@Click(R.id.community_message_list_title_back)
	public void back(){
		backAction(mFragmentId);
	}
	
	@AfterViews
	public void initView(){
		if (mIsFirstLoad) {
			mCommunityMessageListAdapter = new CommunityMessageListAdapter();
			mPullToRefreshListView.setAdapter(mCommunityMessageListAdapter);
			mCommunityMessageListAdapter.setAdatperCallBack(new AdapterCallBack() {
				@Override
				public void onAvatorClick(String userNo) {
//					UserCommunityFragment.add(userNo, mFragmentId);
					MyCommunityFragment.add(mFragmentId, userNo, null);
				}

				@Override
				public void onCommunityClick(int type,int communityId, int position) {
//					CommunityDetailFragment.add(mFragmentId, communityId,mUserNo);
					boolean is_offical = type == 1 ? true : false;
					CommunityDetailActivity.show(is_offical, communityId,mUserNo,false,-1,mCommunityMessages.get(position).groupId);
				}
			});
			mLoadType = LoadType.load_first;
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					if (mHasUnRead) {
						List<CommunityMessage> localCommunityMessageList  = CommunityMessageManager.getInstance().queryUnRead();
						if (localCommunityMessageList != null && localCommunityMessageList.size() > 0) {
							int size = localCommunityMessageList.size();
							for (int i = 0; i < size; i++) {
								localCommunityMessageList.get(i).parseObject();
							}
							mCommunityMessages.addAll(localCommunityMessageList);
							mCommunityMessageListAdapter.setData(mCommunityMessages);
						}
					}else{
						getCommunityMessageList();
					}
					readCommunityMessage();
				}
			}, CONSTANT.LOAD_DATA_DELAY_TIME);
			mBaseOnScrollListener = new BaseOnScrollListener(new LoadMoreCallBack() {
				@Override
				public void loadMore() {
					mPullToRefreshListView.startLoadMore();
					mLoadType = LoadType.load_more;
					getCommunityMessageList();
				}
			});
			mPullToRefreshListView.setOnScrollListener(mBaseOnScrollListener);
			mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
				@Override
				public void onRefresh(PullToRefreshBase<ListView> refreshView) {
					mLoadType = LoadType.load_refresh;
					getCommunityMessageList();
				}
			});
		}
	}

	private void getCommunityMessageList(){
		if (mIsLoading) {
			return ;
		}
		if (mLoadType == LoadType.load_more) {
			start += pageSize;
//			limit += pageSize;
		}else{
			start = 0;
			limit = pageSize;
		}
		mIsLoading = true;
		BaseListJsonHandler<CommunityMessageResponse> response = new BaseListJsonHandler<CommunityMessageResponse>() {
			public void onStart() {
				if (mLoadType == LoadType.load_first) {
					showProgressBar(mProgressLayout);
				}
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, CommunityMessageResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					if (response.getData() != null) {
						if (mLoadType == LoadType.load_more) {
							if (mCommunityMessages.size() == response.getData().getCount()) {
								mBaseOnScrollListener.mIsEnd = true;
							}
						}else{
							mCommunityMessages.clear();
						}
						List<CommunityMessage> list = response.getData().getList();
						if (list != null) {
							mCommunityMessages.addAll(list);
						}
						if (mCommunityMessages.size() > 0) {
							mEmptyLayout.setVisibility(View.GONE);
						}else{
							mEmptyLayout.setVisibility(View.VISIBLE);
						}
						mCommunityMessageListAdapter.setData(mCommunityMessages);
					}
					
				}else {
					BaseApplication.showToast(response.getErrMsg());
				}
				afterLoading();
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					CommunityMessageResponse errorResponse) {
				afterLoading();
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected CommunityMessageResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				return mGson.fromJson(rawJsonData,CommunityMessageResponse.class);
			}
		};
		List<Conds> conds = new ArrayList<Conds>();
		HttpManager.getInstance().getCommunityMessageList(BaseApplication.mUserNo,start,limit, null,conds, response);
	}
	
	private void readCommunityMessage(){
		BaseListJsonHandler<BaseResponse> response = new BaseListJsonHandler<BaseResponse>() {
			public void onStart() {
				if (mLoadType == LoadType.load_first) {
//					showProgressBar(mProgressLayout);
				}
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, BaseResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					AppShortCutUtil.addNumShortCut(BaseApplication.mContext, SplashActivity.class, true,"0", true);
					CommunityMessageManager.getInstance().clear(CommunityMessage.class);
				}else {
					BaseApplication.showToast(response.getErrMsg());
				}
				afterLoading();
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					BaseResponse errorResponse) {
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected BaseResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
//				afterLoading();
				return mGson.fromJson(rawJsonData,BaseResponse.class);
			}
		};
		HttpManager.getInstance().readCommunityMessage(BaseApplication.mUserNo, response);
	
	}

	public void afterLoading(){
		mIsLoading = false;
		hideProgressBar(mProgressLayout);
		if(mLoadType == LoadType.load_more){
			if (mBaseOnScrollListener.mIsEnd) {
				mPullToRefreshListView.endLoadMore(BaseApplication.getResString(R.string.message_no_more_data));
			}else{
				mPullToRefreshListView.stopLoadMore();
			}
		}
		if(mPullToRefreshListView != null){
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					if(mPullToRefreshListView != null){
						mPullToRefreshListView.onRefreshComplete();
						LogUtil.d("--onRefreshComplete afterloading");
					}
				}
			}, 1000);
		}
	
	}
	Dialog mSearchDialog;
	String mWord;
	EditText mSearchExt;
	public void showSearchDialog(){
		RelativeLayout shareLayout = (RelativeLayout) mInflater.inflate(R.layout.search_pop, null);
		if(mSearchDialog != null && mSearchDialog.isShowing()){
			return;
		}
		mSearchDialog = new Dialog(BaseApplication.mCurrentActivity, R.style.fullscreendialog);
		mSearchDialog.setCanceledOnTouchOutside(true);
		mSearchDialog.setContentView(shareLayout);
		ImageView back = (ImageView) shareLayout.findViewById(R.id.search_pop_back);
		mSearchExt = (EditText)shareLayout.findViewById(R.id.search_pop_ext);
//		searchExt.setHint(R.string.search_product_hint);
		mSearchExt.setText(mWord);
		mSearchExt.setOnEditorActionListener(new OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//				if(actionId == EditorInfo.IME_ACTION_SEARCH){
				if (event == null) {
//					searchAction();
				}
//				}
				return false;
			}
		});
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mSearchDialog.dismiss();
			}
		});
		Window window = mSearchDialog.getWindow();
		window.setBackgroundDrawable(new ColorDrawable(0x00000000));
		window.setLayout(BaseApplication.mScreenWidth, BaseApplication.mScreenHeight);
		window.setGravity(Gravity.TOP);
		window.setWindowAnimations(R.style.look_share_show);
		window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN
				| WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		mSearchDialog.show();
		window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN| WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
//		mHandler.postDelayed(new Runnable() {
//			@Override
//			public void run() {
//				showSoftKeyBoard(searchExt, true);
//			}
//		}, CONSTANT.LOAD_DATA_DELAY_TIME);
	}
	@Override
	public void clear() {
		// TODO Auto-generated method stub
	}

	@Override
	public void initArgs(Bundle args) {
		if (args != null) {
			mFragmentId = args.getInt(CONSTANT.ARGS.FRAGMENT_ID);
			mUserNo = args.getString(CONSTANT.ARGS.USER_NO);
			mHasUnRead = args.getBoolean(CONSTANT.ARGS.HAS_UNREAD);
		}
	}

}
